package com.alibaba.nacos.config.server.jpa;

import java.util.Optional;

import static com.alibaba.nacos.core.utils.Constants.STANDALONE_MODE_PROPERTY_NAME;

import com.alibaba.nacos.config.server.jpa.entity.RolesEntity;
import com.alibaba.nacos.config.server.jpa.entity.UsersEntity;
import com.alibaba.nacos.config.server.jpa.repository.RolesRepository;
import com.alibaba.nacos.config.server.jpa.repository.UsersRepository;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * The type of nacos-all.
 *
 * @author 问道于盲
 * @date 2020-03-12
 */
@Component
public class InitHelper implements InitializingBean {

    @Autowired
    private UsersRepository usersRepository;

    @Autowired
    private RolesRepository rolesRepository;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        String rolename = "ROLE_ADMIN";
        String username = "nacos";
        //密码为nacos
        String password = "$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu";

        transactionTemplate.execute(transactionStatus -> {
            try{
                addUser(username, password);
            }catch (Exception e){
                transactionStatus.setRollbackOnly();
            }
            return true;
        });

        transactionTemplate.execute(transactionStatus -> {
            try{
                addRole(rolename, username);
            }catch (Exception e){
                transactionStatus.setRollbackOnly();
            }
            return true;
        });

    }

    /**
     * 添加默认用户
     * @param username
     * @param password
     */
    private void addUser(String username, String password) {
        Optional<UsersEntity> userOptional = usersRepository.getByUsername(username);
        if (!userOptional.isPresent()){
            UsersEntity user = new UsersEntity(username, true, password);
            usersRepository.save(user);
        }
    }

    /**
     * 添加默认角色
     * @param rolename
     * @param username
     */
    private void addRole(String rolename, String username) {
        Optional<RolesEntity> roleOptional = rolesRepository.findByRoleAndUsername(rolename, username);

        if (!roleOptional.isPresent()){
            RolesEntity role = new RolesEntity(rolename,username);
            rolesRepository.save(role);
        }
    }

}
